package com.focusai.efairy.ui.activity.project;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;

import com.focusai.efairy.R;
import com.focusai.efairy.model.manager.CacheManager;
import com.focusai.efairy.model.project.OnItemTailClickListener;
import com.focusai.efairy.model.project.OnitemTitleClickListener;
import com.focusai.efairy.model.project.ProjectItem;
import com.focusai.efairy.model.project.ProjectManagerDetail;
import com.focusai.efairy.model.request.GetDevMoreRequest;
import com.focusai.efairy.model.request.GetGmListRequest;
import com.focusai.efairy.model.request.GetProjectManageRequest;
import com.focusai.efairy.model.request.GetUserListRequest;
import com.focusai.efairy.model.response.ProjectManageResponse;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.ui.adapter.project.ProjectInfoTypeViewBinder;
import com.focusai.efairy.ui.adapter.project.ProjectManagerDevItemTypeViewBinder;
import com.focusai.efairy.ui.adapter.project.ProjectManagerGmItemTypeViewBinder;
import com.focusai.efairy.ui.adapter.project.ProjectManagerUserItemTypeViewBinder;
import com.focusai.efairy.ui.adapter.project.ProjectMangagerTailTypeViewBinder;
import com.focusai.efairy.ui.adapter.project.ProjectMangagerTitleTypeViewBinder;
import com.focusai.efairy.ui.base.SwipeBackBaseActivity;
import com.focusai.efairy.utils.Constants;

import java.util.ArrayList;
import java.util.List;

import me.drakeet.multitype.MultiTypeAdapter;

/**
 * Created by luo_guangwen on 2017/8/13.
 */

public class ProjectManagerActivity extends SwipeBackBaseActivity {
    public static final String KEY_PROJECT_ITEM_ID = "key_project_item";
    private static final int REQUEST_CODE_PRO_DETAIL = 0x10;
    private static final int REQUEST_CODE_USER = 0x11;
    private static final int REQUEST_CODE_DEV = 0x12;
    private static final int REQUEST_CODE_GM = 0x13;
    private RecyclerView mRecyclerView;
    private MultiTypeAdapter mAdapter;
    private List<Object> mList;
    private ProjectItem project_info;
    private List<ProjectManageResponse.GmItme> gm_list;
    private List<ProjectManageResponse.UserItem> user_list;
    private List<ProjectManageResponse.DevItem> device_list;
    private String projectId;
    private ProjectManagerDetail.Title userTitle, devTitle, gmTitle;
    private ProjectManagerDetail.Tail userTail, devTail, gmTail;
    private int defaultListSize = 5; //默认每个列表的item数为6

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_project_manager);
        initView();
        setDefaultValues();
        loadData();
    }

    @Override
    protected void initView() {
        mRecyclerView = findView(R.id.rcyc_view);
    }

    @Override
    public void initTitte() {
        setCenterTitleName("项目详情");
    }

    @Override
    protected void setDefaultValues() {
        if (getIntent() != null) {
            projectId = getIntent().getStringExtra(KEY_PROJECT_ITEM_ID);
        }
        if (TextUtils.isEmpty(projectId)) {
            showToast("项目id传入为空");
            finish();
        }
        mAdapter = new MultiTypeAdapter();
        mList = new ArrayList<>();
        gm_list = new ArrayList<>();
        user_list = new ArrayList<>();
        device_list = new ArrayList<>();
        devTitle = new ProjectManagerDetail.Title(ProjectManageResponse.DevItem.class, "设备列表");
        userTitle = new ProjectManagerDetail.Title(ProjectManageResponse.UserItem.class, "用户列表");
        gmTitle = new ProjectManagerDetail.Title(ProjectManageResponse.GmItme.class, "管理员列表");
        devTail = new ProjectManagerDetail.Tail(ProjectManageResponse.DevItem.class);
        userTail = new ProjectManagerDetail.Tail(ProjectManageResponse.UserItem.class);
        gmTail = new ProjectManagerDetail.Tail(ProjectManageResponse.GmItme.class);
        ProjectMangagerTitleTypeViewBinder titleTypeViewBinder = new ProjectMangagerTitleTypeViewBinder();
        titleTypeViewBinder.setOnItemClickListener(onitemTitleClickListener);
        mAdapter.register(ProjectManagerDetail.Title.class, titleTypeViewBinder);

        ProjectMangagerTailTypeViewBinder tailTypeViewBinder = new ProjectMangagerTailTypeViewBinder();
        tailTypeViewBinder.setOnItemClickListener(onItemTailClickListener);
        mAdapter.register(ProjectManagerDetail.Tail.class, tailTypeViewBinder);

        ProjectInfoTypeViewBinder projectInfoTypeViewBinder = new ProjectInfoTypeViewBinder(getContext());
        projectInfoTypeViewBinder.setOnItemClickListener(proItemClickListener);
        mAdapter.register(ProjectItem.class, projectInfoTypeViewBinder);

        ProjectManagerDevItemTypeViewBinder devItemTypeViewBinder = new ProjectManagerDevItemTypeViewBinder(getContext());
        devItemTypeViewBinder.setOnItemClickListener(devItemClickListener);
        mAdapter.register(ProjectManageResponse.DevItem.class, devItemTypeViewBinder);

        ProjectManagerUserItemTypeViewBinder userItemTypeViewBinder = new ProjectManagerUserItemTypeViewBinder(getContext());
        userItemTypeViewBinder.setOnItemClickListener(usrItemClickListener);
        mAdapter.register(ProjectManageResponse.UserItem.class, userItemTypeViewBinder);

        ProjectManagerGmItemTypeViewBinder gmItemTypeViewBinder = new ProjectManagerGmItemTypeViewBinder(getContext());
//        gmItemTypeViewBinder.setOnItemClickListener(gmItemClickListener);
        mAdapter.register(ProjectManageResponse.GmItme.class, gmItemTypeViewBinder);

        mAdapter.setItems(mList);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);

    }

    @Override
    protected void loadData() {
        showSingleDialog(getResources().getString(R.string.loading));
        HttpManager.getInstance().sendRequest(new GetProjectManageRequest(projectId, new Response.Listener<ProjectManageResponse>() {
            @Override
            protected void onSuccess(ProjectManageResponse response) {
                closeSingleDialog();
                if (response != null) {
                    updateData(response);
                }
            }

            @Override
            protected void onFail(NetworkException exception) {
                closeSingleDialog();
                doException(exception);
            }
        }));
    }

    public void updateData(ProjectManageResponse response) {
        if (response.project_info != null) {
            this.project_info = response.project_info;
            mList.add(this.project_info);
        }
        if (response.device_list != null) {
            this.device_list.clear();
            this.device_list.addAll(response.device_list);
        }
        if (response.user_list != null) {
            this.user_list.clear();
            this.user_list.addAll(response.user_list);
        }
        if (response.gm_list != null) {
            this.gm_list.clear();
            this.gm_list.addAll(response.gm_list);
        }
        gmTitle.count = this.project_info.efairyproject_total_gms;
        devTitle.count = this.project_info.efairyproject_total_devices;
        userTitle.count = this.project_info.efairyproject_total_users;
        if (!String.valueOf(project_info.efairyproject_creator_id).equals(CacheManager.getUserId())){
            gmTitle.showLable = false;
        }
        notifyDataSetChanged();
    }

    private void notifyDataSetChanged() {
        mList.clear();
        mList.add(this.project_info);

        //管理员
        mList.add(gmTitle);
        mList.addAll(this.gm_list);
        if (this.gm_list.size() < gmTitle.count) {
            mList.add(gmTail);
        }

        //设备
        mList.add(devTitle);
        mList.addAll(this.device_list);
        if (this.device_list.size() < devTitle.count) {
            mList.add(devTail);
        }

        //用户
        userTitle.lable="用户管理&设备分配";
        mList.add(userTitle);
        mList.addAll(this.user_list);
        if (this.user_list.size() <  userTitle.count) {
            mList.add(userTail);
        }

        mAdapter.notifyDataSetChanged();
    }

    private OnItemTailClickListener onItemTailClickListener = new OnItemTailClickListener() {
        @Override
        public void onItemClickListener(Class<?> classType, boolean isloadMore) {
            if (classType == ProjectManageResponse.DevItem.class) {
                loadMoreDevices(isloadMore);
            } else if (classType == ProjectManageResponse.UserItem.class) {
                loadMoreUser(isloadMore);
            } else if (classType == ProjectManageResponse.GmItme.class) {
                loadMoreGm(isloadMore);
            }
        }
    };

    private OnitemTitleClickListener onitemTitleClickListener = new OnitemTitleClickListener() {
        @Override
        public void onItemClickListener(Class<?> classType) {
            if (classType == ProjectManageResponse.DevItem.class) {
                Intent intent = new Intent(getContext(),ProjectDevListActivity.class);
                intent.putExtra(ProjectDevListActivity.KEY_PROJECT_ID,projectId);
                intent.putExtra(ProjectDevListActivity.KEY_PROJECT_ITEM,project_info);
                startActivityForResult(intent,REQUEST_CODE_DEV);
            } else if (classType == ProjectManageResponse.UserItem.class) {
                Intent intent = new Intent(getContext(),ProjectUserListActivity.class);
                intent.putExtra(ProjectUserListActivity.KEY_PROJECT_ID,projectId);
                intent.putExtra(ProjectUserListActivity.KEY_PROJECT_ITEM,project_info);
                startActivityForResult(intent,REQUEST_CODE_USER);
            } else if (classType == ProjectManageResponse.GmItme.class) {
                Intent intent = new Intent(getContext(),ProjectGmListActivity.class);
                intent.putExtra(ProjectGmListActivity.KEY_PROJECT_ID,projectId);
                intent.putExtra(ProjectGmListActivity.KEY_PROJECT_ITEM,project_info);
                startActivityForResult(intent,REQUEST_CODE_GM);
            }
        }
    };

    private ProjectManagerUserItemTypeViewBinder.OnItemClickListener usrItemClickListener = new ProjectManagerUserItemTypeViewBinder.OnItemClickListener() {
        @Override
        public void onItemClick(ProjectManageResponse.UserItem item) {
            Intent intent = new Intent(getContext(),ProjectEditUserActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ProjectEditUserActivity.KEY_ITEM_USER,item);
            bundle.putString(ProjectEditUserActivity.KEY_PROJECT_ID,projectId);
            bundle.putBoolean(Constants.KEY_DETAIL,true);
            intent.putExtras(bundle);
            startActivityForResult(intent,REQUEST_CODE_USER);
        }
    };

    private ProjectManagerDevItemTypeViewBinder.OnItemClickListener devItemClickListener = new ProjectManagerDevItemTypeViewBinder.OnItemClickListener() {
        @Override
        public void onItemClick(ProjectManageResponse.DevItem item) {
            Intent intent = new Intent(getContext(), ProjectAddDeviceActivity.class);
            intent.putExtra(ProjectAddDeviceActivity.KEY_DEV_ITEM,item);
            intent.putExtra(ProjectAddDeviceActivity.OPENTYPE,true);
            intent.putExtra(ProjectAddDeviceActivity.KEY_PROJECT_ID,projectId);
            intent.putExtra(Constants.KEY_DETAIL,true);
            startActivityForResult(intent, REQUEST_CODE_DEV);
        }
    };

    private ProjectManagerGmItemTypeViewBinder.OnItemClickListener gmItemClickListener = new ProjectManagerGmItemTypeViewBinder.OnItemClickListener() {
        @Override
        public void onItemClick(ProjectManageResponse.GmItme item) {

        }
    };

    private ProjectInfoTypeViewBinder.OnItemClickListener proItemClickListener = new ProjectInfoTypeViewBinder.OnItemClickListener() {
        @Override
        public void onItemClick(ProjectItem item) {
            Intent intent = new Intent(mContext, ProjectAddorEditActivity.class);
            intent.putExtra(ProjectAddorEditActivity.PROJECT_ITEM, item);
            intent.putExtra(ProjectAddorEditActivity.OPENTYPE, true);
            startActivityForResult(intent, REQUEST_CODE_PRO_DETAIL);
        }
    };
    private void loadMoreDevices(boolean loadMore) {
        if (!loadMore) {
            if (this.device_list.size() > defaultListSize + 1) {
                List<ProjectManageResponse.DevItem> list = new ArrayList<>();
                for (int i = 0; i <= defaultListSize; i++) {
                    list.add(this.device_list.get(i));
                }
                this.device_list.clear();
                this.device_list.addAll(list);
                this.devTail.hasMore = true;
                notifyDataSetChanged();
            }
        } else if (this.device_list.size() > 0) {
            showSingleDialog("正在加载数据..");
            HttpManager.getInstance().sendRequest(new GetDevMoreRequest(projectId, this.device_list.get(this.device_list.size() - 1).efairydevice_id,
                    "", new Response.Listener<ProjectManageResponse.DevItems>() {
                @Override
                protected void onSuccess(ProjectManageResponse.DevItems response) {
                    closeSingleDialog();
                    if (response != null) {
                        if (response.device_list != null) {
                            ProjectManagerActivity.this.device_list.addAll(response.device_list);
                        }
                        if (response.efairyproject_total_devices == ProjectManagerActivity.this.device_list.size()) {
                            devTail.hasMore = false;
                        } else {
                            devTail.hasMore = true;
                        }
                        notifyDataSetChanged();
                    }
                }

                @Override
                protected void onFail(NetworkException exception) {
                    closeSingleDialog();
                }
            }));
        }
    }

    private void loadMoreUser(boolean loadMore) {
        if (!loadMore) {
            if (this.user_list.size() > defaultListSize + 1) {
                List<ProjectManageResponse.UserItem> list = new ArrayList<>();
                for (int i = 0; i <= defaultListSize; i++) {
                    list.add(this.user_list.get(i));
                }
                this.user_list.clear();
                this.user_list.addAll(list);
                this.userTail.hasMore = true;
                notifyDataSetChanged();
            }
        } else if (this.user_list.size() > 0) {
            showSingleDialog("正在加载数据..");
            HttpManager.getInstance().sendRequest(new GetUserListRequest(projectId, this.user_list.get(this.user_list.size() - 1).efairyuser_id,
                    "", new Response.Listener<ProjectManageResponse.UserItems>() {
                @Override
                protected void onSuccess(ProjectManageResponse.UserItems response) {
                    closeSingleDialog();
                    if (response != null) {
                        if (response.user_list != null) {
                            ProjectManagerActivity.this.user_list.addAll(response.user_list);
                        }
                        if (response.efairyproject_total_users == ProjectManagerActivity.this.user_list.size()) {
                            userTail.hasMore = false;
                        } else {
                            userTail.hasMore = true;
                        }
                        notifyDataSetChanged();
                    }
                }

                @Override
                protected void onFail(NetworkException exception) {
                    closeSingleDialog();
                }
            }));
        }
    }

    private void loadMoreGm(boolean loadMore) {
        if (!loadMore) {
            if (this.gm_list.size() > defaultListSize + 1) {
                List<ProjectManageResponse.GmItme> list = new ArrayList<>();
                for (int i = 0; i <= defaultListSize; i++) {
                    list.add(this.gm_list.get(i));
                }
                this.gm_list.clear();
                this.gm_list.addAll(list);
                this.gmTail.hasMore = true;
                notifyDataSetChanged();
            }
        } else if (this.gm_list.size() > 0) {
            showSingleDialog("正在加载数据..");
            HttpManager.getInstance().sendRequest(new GetGmListRequest(projectId, this.gm_list.get(this.gm_list.size() - 1).efairyuser_id,
                    "", new Response.Listener<ProjectManageResponse.GmItems>() {
                @Override
                protected void onSuccess(ProjectManageResponse.GmItems response) {
                    closeSingleDialog();
                    if (response != null) {
                        if (response.gm_list != null) {
                            ProjectManagerActivity.this.gm_list.addAll(response.gm_list);
                        }
                        if (response.efairyproject_total_gms == ProjectManagerActivity.this.gm_list.size()) {
                            gmTail.hasMore = false;
                        } else {
                            gmTail.hasMore = true;
                        }
                        notifyDataSetChanged();
                    }
                }

                @Override
                protected void onFail(NetworkException exception) {
                    closeSingleDialog();
                }
            }));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK){
            switch (requestCode){
                case REQUEST_CODE_DEV:
                case REQUEST_CODE_USER:
                case REQUEST_CODE_GM:
                case REQUEST_CODE_PRO_DETAIL:
                    loadData();
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
